package com.lianniu.mgr.baseService.file.impl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.commons.fileupload.FileItem;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.lianniu.mgr.baseService.file.BaseUtil;
import com.lianniu.mgr.baseService.file.IFileUploadService;

@Service("fileUploadService")
public class FileUploadService implements IFileUploadService{
	
	//储存照片地址
	//private static String urlPath = "/home/firmboy/weixin-tomcat/webapps/weixin/img/";
	private static String urlPath = "/mnt/tomcat/weixin/webapps/ROOT/img/";

	// private static String urlPath = "D://";
	//读取照片地址
	//private static String imgPath = "http://47.95.11.244/weixin/img/";
	private static String imgPath = "http://www.nashannacha.com:8081/img/";

	@Override
	public String fileUploadMulti(MultipartFile file, String serverName,String realPath,
			String fileURL,byte[] byteList) {
		fileURL=fileURL.trim();
		SimpleDateFormat fileNameFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileNameAll = file.getOriginalFilename();
		String fileName="";
		if(!fileNameAll.equals("")){
		String ex = fileNameAll.substring(fileNameAll.lastIndexOf("."));
		long name = System.currentTimeMillis();
			fileName = fileNameFormat.format(new Date())+"_"+name;
			fileName = fileName+ex;
		}
		// 图片保存目录路径
//		String uploadPath = new StringBuffer(request.getSession().getServletContext().getRealPath("/")).toString();
		//product/
		// 图片保存目录URL
		String savePath = (fileURL.startsWith("/")?"":"/")+fileURL;
		String uploadPath = BaseUtil.getStaticFilePathForUpload(serverName,realPath,fileURL);
		List<String> fileType=uploadType();
		String picPath = "";
		if(!(file.getOriginalFilename()==null ||"".equals(file.getOriginalFilename()))){
			picPath=savePath+fileName;
			this.getFile(file,fileType,uploadPath,fileName,byteList);
		}
		return picPath;
	}
	@Override
	public String fileUploadByte(String serverName,String realPath,String fileName,
			String fileURL,byte[] byteList) {
		if(byteList==null || byteList.length == 0)return"";
		fileURL=fileURL.trim();
		String savePath = (fileURL.startsWith("/")?"":"/")+fileURL;
		String uploadPath = BaseUtil.getStaticFilePathForUpload(serverName,realPath,fileURL);
		List<String> fileType=uploadType();
		String generatedName = this.generateFileName(fileName);
//		this.getFile(null,fileType,uploadPath,generatedName,byteList);
//		return "/LianniuManager/mnt/b2b/"+savePath+generatedName;
		this.getFile(null,fileType,urlPath,generatedName,byteList);
		return imgPath+generatedName;
	}
	private String generateFileName(String originalName){
	  String fileName = originalName;
	  String ex = fileName.substring(fileName.lastIndexOf("."));
	  String generatedName = "";
	  Random ran = new Random();
      SimpleDateFormat fileNameFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
      generatedName = fileNameFormat.format(new Date())+"_"+ran.nextInt(1000);
      generatedName = generatedName+ex;
      return generatedName;
	}
	private File getFile(MultipartFile imgFile,List<String> fileTypes,String savePath,String fileName,byte[]byteList){
		String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
	    File file = new File(savePath);
	    file.setReadable(true);
	    file.setWritable(true);
	    if (!file.exists()) {
	    	file.mkdirs();
		}
	    File picFile = new File(savePath,fileName);
		//对扩展名进行小写转换
		ext = ext.toLowerCase();
		if(true){
			try{
				FileOutputStream fileOS = new FileOutputStream(picFile);
				fileOS.write(byteList);
				fileOS.close();
			}catch(IllegalStateException e){
				e.printStackTrace();
			}catch(IOException e){
				e.printStackTrace();
			}
		}
		return file;
	}
	/**
	 * 允许上传的文件类型
	 * @return
	 */
	private List<String> uploadType(){
		List<String> list= new ArrayList<String>();
		list.add("jpg");
		list.add("jpeg");
		list.add("bmp");
		list.add("gif");
		list.add("png");
		list.add("xls");
		list.add("xlsx");
		return list;
	}
	@Override
	public byte[] getRemoteFile(String serverName,String realPath,String picPath) {
		try {
			String path=BaseUtil.getStaticFilePathForUpload(serverName,realPath, picPath);
			File file = new File(path);
			FileInputStream fis = new FileInputStream(file);
			BufferedInputStream buff = new BufferedInputStream(fis);
			List<Byte> list = new ArrayList<Byte>();
			byte[] cache = new byte[1024];
			int read = 0;
			while((read=buff.read(cache))>0){
				for(int i =0 ;i< read ; i++){
					list.add(cache[i]);
				}
			}
			byte[] re = new byte[list.size()];
			for(int i = 0;i < list.size() ; i++){
				re[i] = list.get(i);
			}
			return re;
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * item的write方法不可用，因为内容并没有放在内存中
	 */
	@Override
	public String fileUploadItem(FileItem item,String serverName,String upPath,String filePath,byte[] byteList){
		String uploadPath =  BaseUtil.getStaticFilePathForUpload(serverName,upPath,filePath);
		// 检查目录
		File uploadDir = new File(uploadPath);
		uploadDir.setWritable(true);
		uploadDir.setReadable(true);
		if (!uploadDir.isDirectory() || !uploadDir.exists()) {
			//out.println(alertMsg("上传图片保存的目录不存在。"));
			//return;
			uploadDir.mkdirs();
			//uploadDir.setExecutable(true);
			if(isLinux()){
				try {
					Runtime.getRuntime().exec("chmod 777 " + uploadPath);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		// 检查目录写权限
		if (!uploadDir.canWrite()) {
			return "上传图片保存的目录没有写权限。";
		}
		SimpleDateFormat folderNameFormat = new SimpleDateFormat("yyyyMMdd");
		String realPath = uploadPath + folderNameFormat.format(new Date());
		File folder = new File(realPath);
		boolean flag = folder.exists();
		// 确认文件夹是否已经存在
		if(!flag){
			flag = folder.mkdirs();
//			folder.setExecutable(true);
			if(isLinux()){
				try {
					Runtime.getRuntime().exec("chmod 777 " + realPath);
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}
		// 创建文件夹并上传图片
		if(flag){
			String fileName=item.getName();
			String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
			SimpleDateFormat fileNameFormat = new SimpleDateFormat("yyyyMMddHHmmss");					
			String newFileName = fileNameFormat.format(new Date()) + "_"+ new Random().nextInt(1000) + "." + fileExt;						
			File uploadedFile = new File(realPath, newFileName);	
			try {
				FileOutputStream fileOS = new FileOutputStream(uploadedFile);
				fileOS.write(byteList);
				fileOS.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
//			resizeImg = uploadedFile.getPath();
//			resizeImg = resizeImg.replaceAll("\\\\", "/");
			return "/"+folderNameFormat.format(new Date())+"/"+newFileName;						
		}else{
			return "文件夹创建失败，请确认磁盘没有写保护并且空件足够";
		}	
	}
	private boolean isLinux() {
		String os = System.getProperty("os.name").toLowerCase();
		
		if (os.indexOf("linux") != -1) return true;
		return false;
	}
}
